package cn.mengfly.testnrz.nio;

import cn.mengfly.testnrz.util.IOUtil;

import java.io.File;
import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * @author Mengfly
 */
public class NioSendClient {

    private Charset charset = Charset.forName("UTF-8");

    public void sendFile() throws Exception {
        String sourcePath = NioDemoConfig.getPath("client.txt");
        String destFile = NioDemoConfig.getPath("server.txt");

        File file = new File(sourcePath);
        if(!file.exists()) {
            System.out.println("文件不存在");
            return;
        }
        FileChannel fileChannel = new FileInputStream(file).getChannel();
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.socket().connect(new InetSocketAddress(NioDemoConfig.SOCKET_IP, NioDemoConfig.SOCKET_PORT));
        socketChannel.configureBlocking(false);
        System.out.println("连接服务器...");
        while(!socketChannel.finishConnect()) {
            // 自旋
        }
        System.out.println("成功连接服务器");
        ByteBuffer fileNameBuffer = charset.encode(destFile);
        socketChannel.write(fileNameBuffer);
        int i = 0;
//        while (i < 60000) {
//            i++;
//        }
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        System.out.println(file.length());
        buffer.putLong(file.length());

        buffer.flip();
        socketChannel.write(buffer);
        buffer.clear();
        // 发送文件内容
        int length = 0;
        long progress = 0;
        while ((length = fileChannel.read(buffer)) > 0) {
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
            progress += length;
            System.out.println("| " + (100 * progress/file.length()) + "% |");
        }
        if (length == -1) {
            IOUtil.close(fileChannel);
            socketChannel.shutdownOutput();
        }
    }

    public static void main(String[] args) throws Exception {
        NioSendClient client = new NioSendClient();
        client.sendFile();
    }
}
